<template>
  <view class="file-display-container">
    <!-- 文件列表 -->
    <view class="file-list">
      <view 
        v-for="(file, index) in files" 
        :key="index" 
        class="file-card"
        :style="{ width: cardWidth }"
      >
        <!-- 删除按钮 -->
        <view class="delete-btn" @click="handleDelete(index)">
          <uni-icons type="close" size="12" color="#fff"></uni-icons>
        </view>
        
        <!-- 文件缩略图 -->
        <view class="file-thumbnail" @click="handleFileClick(file)">
          <!-- 图片文件 -->
          <image 
            v-if="isImage(file.fileType)" 
            :src="file.filePath" 
            mode="aspectFill"
            class="thumbnail-image"
          ></image>
          
          <!-- 其他文件 -->
          <view v-else class="file-icon-container" :style="{ backgroundColor: getFileColor(file.fileType) }">
            <uni-icons :type="getFileIcon(file.fileType)" size="42" color="#fff"></uni-icons>
            <text class="file-extension">{{ getFileExtension(file.fileName) }}</text>
          </view>
        </view>
        
        <!-- 文件信息 -->
        <view class="file-details">
          <text class="file-name" :title="file.fileName">{{ file.fileName }}</text>
          <uni-icons type="download" v-if="isImage(file.fileType)" size="12" color="#3498db" @click="downloadFile(file)" class="download-icon" ></uni-icons>
		  <!-- <text class="file-info">{{ formatFileSize(file.size) }}</text> -->
        </view>
        
        <!-- 操作按钮 -->
        <!-- <view class="file-actions">
          <view 
            v-if="isImage(file.fileType)" 
            class="action-btn" 
            @click="previewImage(file)"
          >
            <uni-icons type="eye" size="20" color="#3498db"></uni-icons>
            <text>预览</text>
          </view>
          <view class="action-btn" @click="downloadFile(file)">
            <uni-icons type="download" size="20" color="#3498db"></uni-icons>
            <text>下载</text>
          </view>
        </view> -->
      </view>
    </view>
    
    <!-- 空状态 -->
    <view v-if="files.length === 0" class="empty-state">
      <uni-icons type="cloud-upload" size="32" color="#bdc3c7"></uni-icons>
      <text class="empty-text">暂无附件</text>
    </view>
  </view>
</template>

<script>
export default {
  name: "FileDisplay",
  props: {
    // 文件列表
    fileList: {
      type: Array,
      default: () => []
    },
    // 每行显示文件数 (用于计算卡片宽度)
    itemsPerRow: {
      type: Number,
      default: 4
    },
	// 文件标题截取字数
	nameSize: {
		type: Number,
		default: 7
	}
  },
  computed: {
    // 计算卡片宽度
    cardWidth() {
      const spacing = 5; // 间距
      const widthPercentage = 100 / this.itemsPerRow;
      return `calc(${widthPercentage}% - ${spacing}px)`;
    },
	files() {
		if(this.fileList && this.fileList.length > 0) {
			return this.fileList.map(file => {
				return {...file }
			})
		}
		return [];
	}
  },
  methods: {
    // 判断是否为图片
    isImage(type) {
      return type && type.startsWith('image/');
    },
    
    // 获取文件图标类型
    getFileIcon(type) {
      if (!type) return 'help';
      
      if (type.includes('pdf')) return 'pdf';
      if (type.includes('word')) return 'word';
      if (type.includes('excel') || type.includes('sheet')) return 'excel';
      if (type.includes('powerpoint') || type.includes('presentation')) return 'ppt';
      if (type.includes('zip') || type.includes('rar')) return 'zip';
      if (type.includes('text') || type.includes('plain')) return 'text';
      
      return 'file';
    },
    
    // 获取文件颜色
    getFileColor(type) {
      const colors = {
        'image': '#3498db',
        'pdf': '#e74c3c',
        'word': '#2c81ba',
        'excel': '#27ae60',
        'ppt': '#e67e22',
        'zip': '#8e44ad',
        'text': '#7f8c8d',
        'default': '#3498db'
      };
      
      if (!type) return colors.default;
      
      if (type.includes('image')) return colors.image;
      if (type.includes('pdf')) return colors.pdf;
      if (type.includes('word')) return colors.word;
      if (type.includes('excel') || type.includes('sheet')) return colors.excel;
      if (type.includes('powerpoint') || type.includes('presentation')) return colors.ppt;
      if (type.includes('zip') || type.includes('rar')) return colors.zip;
      if (type.includes('text') || type.includes('plain')) return colors.text;
      
      return colors.default;
    },
    
    // 获取文件扩展名
    getFileExtension(name) {
      if (!name) return '';
      const dotIndex = name.lastIndexOf('.');
      if (dotIndex === -1) return '';
      return name.substring(dotIndex + 1).toUpperCase();
    },
    
    // 格式化文件大小
    formatFileSize(bytes) {
      if (bytes === 0) return '0 B';
      const k = 1024;
      const sizes = ['B', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    },
    
    // 处理文件点击
    handleFileClick(file) {
      if (this.isImage(file.fileType)) {
        this.previewImage(file);
      } else {
        this.downloadFile(file);
      }
    },
    
    // 预览图片
    previewImage(file) {
      if (!this.isImage(file.fileType)) return;
      
      // 在Uniapp中可以使用uni.previewImage
      uni.previewImage({
        urls: this.files
          .filter(f => this.isImage(f.fileType))
          .map(f => f.filePath),
        current: file.filePath
      });
      
      // 触发预览事件
      this.$emit('preview', file);
    },
    
    // 下载文件
    downloadFile(file) {
      // 触发下载事件
      this.$emit('download', file);
      
      // 在Uniapp中可以使用uni.downloadFile
      uni.showLoading({ title: '下载中...', mask: true });
      
      uni.downloadFile({
        url: file.filePath,
        success: (res) => {
          uni.hideLoading();
          if (res.statusCode === 200) {
            uni.saveFile({
              tempFilePath: res.tempFilePath,
              success: (saveRes) => {
                uni.showToast({
                  title: '文件保存成功',
                  icon: 'success'
                });
                console.log('文件保存路径:', saveRes.savedFilePath);
              },
              fail: () => {
                uni.showToast({
                  title: '保存文件失败',
                  icon: 'none'
                });
              }
            });
          } else {
            uni.showToast({
              title: '下载失败',
              icon: 'none'
            });
          }
        },
        fail: () => {
          uni.hideLoading();
          uni.showToast({
            title: '下载失败',
            icon: 'none'
          });
        }
      });
    },
    
    // 删除文件
    handleDelete(index) {
      // 触发删除事件
      this.$emit('delete', index);
    }
  }
};
</script>

<style lang="scss" scoped>
.file-display-container {
  width: 100%;
  padding: 15rpx;
}

.file-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
  justify-content: flex-start;
}

.file-card {
  background-color: #fff;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 3rpx 10rpx rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  position: relative;
  margin-bottom: 15rpx;
  
  &:hover {
    transform: translateY(-5rpx);
    box-shadow: 0 5rpx 15rpx rgba(0, 0, 0, 0.12);
  }
}

.delete-btn {
  position: absolute;
  top: 10rpx;
  right: 10rpx;
  width: 28rpx;
  height: 28rpx;
  border-radius: 50%;
  // background-color: rgba(231, 76, 60, 0.85);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.9);
  }
}

.file-thumbnail {
  height: 60rpx;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f8fafc;
  overflow: hidden;
  position: relative;
}

.thumbnail-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.file-icon-container {
  width: 90rpx;
  height: 90rpx;
  border-radius: 12rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
}

.file-extension {
  position: absolute;
  bottom: 8rpx;
  color: rgba(255, 255, 255, 0.9);
  font-size: 12rpx;
  font-weight: bold;
}

.file-details {
  padding: 12rpx;
  display: flex;
  .download-icon {
	  margin-left: 10rpx;
  }
}

.file-name {
  font-size: 14rpx;
  color: #333;
  font-weight: 500;
  display: block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.file-info {
  font-size: 12rpx;
  color: #7f8c8d;
  display: block;
  margin-top: 4rpx;
}

.file-actions {
  display: flex;
  border-top: 1rpx solid #f0f4f8;
  padding: 8rpx 0;
}

.action-btn {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 6rpx 0;
  color: #3498db;
  font-size: 10rpx;
  
  &:active {
    background-color: #f0f7ff;
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40rpx 20rpx;
  text-align: center;
}

.empty-text {
  color: #7f8c8d;
  font-size: 16rpx;
  margin-top: 15rpx;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .file-thumbnail {
    height: 140rpx;
  }
}

@media (max-width: 480px) {
  .file-thumbnail {
    height: 120rpx;
  }
  
  .file-name {
    font-size: 13rpx;
  }
}
</style>